import React, { useMemo, useState, useEffect } from 'react';
import { loc_dt, uJob, filter_row, loc_str, FindBarBase, useCmd, WaitUmd,
    loc_year, d_sort, save_data, useHigh, MainView, Btn, GridTable, cline, is_empty, for_obj, loc } from 'sui';
import { get_init } from 'trace/cmd';
import { utc_offset } from 'cache';

const InView = () => {
    const [main, setMain] = useState();
    const [opt_find, optFind] = useState();
    const umd = useCmd(null, "trace");
    const [high] = useHigh(140, 100);

    useEffect(() => {
        get_init(optFind)
        setMain(null);
    }, []);

    const getTab = (s, e) => {
        let sy = loc_year(s);
        sy = parseInt(sy, 10);

        let ey = loc_year(e);
        ey = parseInt(ey, 10);

        const ret = [];

        for (let t = sy; t <= ey; t++) {
            ret.push(`${t}`);
        }

        return ret;
    };

    const hfind = (value) => {
        const opt = [];
        const utc = utc_offset();

        const s = value["t_start"];
        const e = value["t_end"];

        for_obj(value, (k, v) => {
            if (k === "t_start" || k === "t_end") {
                return;
            }

            if (!v) {
                return;
            }

            if (k === "time") {
                opt.push({ge: "time", v: loc_str(s), utc: utc});
                opt.push({le: "time", v: loc_str(e), utc: utc});
                return;
            }

            opt.push({eq: k, v: v});
        });

        if (is_empty(opt)) {
            alert(loc("l_307"));
            return;
        }

        opt.push({eq: "line", v: cline()});

        let tab = getTab(s, e);

        umd.startWait();

        const cmd = {
            line: cline(),
            s: loc_dt(s),
            e: loc_dt(e),
            opt: {
                n: tab.join(","),
                obj: "*",
                opt: {desc: true, and: opt},
            }
        };

        uJob(umd.endWait, "goods/intrace", cmd,
            r => {
                d_sort(r, "sn");

                r.forEach((d, i) => d["index"] = i + 1);

                setMain(r);
            },
            e => setMain(null));
    };

    const filteredRows = useMemo(() => {
        const lst = ["sn"]
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_363"), key: 'sn', width: 180},
        {name: loc("l_127"), key: 'num', width: 160},
        {name: loc("l_159"), key: 'away', width: 160},
    ];

    const hExport = () => {
        save_data(main, col, `${loc("l_860")}`, umd);
    };

    const Right = () => {
        return (
            <div className="inline-flex items-center">
                <Btn hcmd={hExport} className="ml-4">{loc("l_298")}</Btn>
            </div>
        );
    };

    const hclear = () => get_init(optFind);

    const getCtl = () => {
        return {
            ctl: [
                {sn: "time", name: loc("l_308"), ctl: "IkFindDate", start: "t_start", end: "t_end"},
            ]
        };
    };

    return (
        <MainView>
            <FindBarBase left={loc("l_158")} right={<Right/>} hcmd={hfind} data={getCtl()} hclear={hclear} cur={opt_find} hfilter={umd.setFilter}/>
            <GridTable col={col} row={filteredRows} high={high - 50}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {InView};
